package com.cbs.android.function.input;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cbs.android.component.application.activity.CBSDialogFragment;

import java.util.List;

/**
 * Created by zyj on 2016/3/19.
 */
public class ButtonDialogFragment extends CBSDialogFragment {
	private List<String> items = null;
	private String title;
	private OnButtonListener onButtonListener;
	private int layout = R.layout.cbs_input_dialog_button;

	private LinearLayout buttonsView;

	public ButtonDialogFragment setTitle(String title) {
		this.title = title;
		return this;
	}

	public ButtonDialogFragment setItems(List<String> items) {
		this.items = items;
		return this;
	}

	public ButtonDialogFragment setOnButtonListener(OnButtonListener onButtonListener) {
		this.onButtonListener = onButtonListener;
		return this;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View view = inflater.inflate(layout, container, false);

		TextView titleView = (TextView) view.findViewById(R.id.cbs_input_dialog_button_title);
		if (title == null || title.equals("")) {
			titleView.setVisibility(View.GONE);
		} else {
			titleView.setVisibility(View.VISIBLE);
			titleView.setText(title);
		}

		buttonsView = (LinearLayout) view.findViewById(R.id.cbs_input_dialog_button_group);
		if (items != null && items.size() > 0) {
			for (int i = 0; i < items.size(); i++) {
				Button button = (Button) inflater.inflate(R.layout.cbs_input_dialog_button_button, buttonsView, false);
				button.setText(items.get(i));
				button.setTag(items.get(i));
				button.setOnClickListener(buttonClick);
				buttonsView.addView(button);
			}
		}


		return view;
	}

	private View.OnClickListener buttonClick = new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			if (view.getTag() == null) {
				return;
			}
			String s = (String) view.getTag();
			onButtonListener.onButtonClick(ButtonDialogFragment.this, items.indexOf(s), s);
		}
	};

	public interface OnButtonListener {
		void onButtonClick(CBSDialogFragment dialogFragment, int which, String item);
	}

}
